package com.yuanqunsoft.alimigration.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONObject;

import com.opensymphony.xwork2.ActionSupport;
import com.yuanqunsoft.alimigration.common.PropertiesUtil;
import com.yuanqunsoft.alimigration.model.Application;
import com.yuanqunsoft.alimigration.model.Module;
import com.yuanqunsoft.alimigration.service.IAllUserService;
import com.yuanqunsoft.alimigration.service.IApplicationService;
import com.yuanqunsoft.alimigration.service.IFileUploadService;
import com.yuanqunsoft.alimigration.service.IModuleService;
import com.yuanqunsoft.alimigration.service.IRuleImplementService;

public class FileUploadAction extends ActionSupport {

    private static final long serialVersionUID = 1L;

    private Application application;
    private Module module;
    private String userName;
    private String appName;
    private List<?> datas;

    private IApplicationService applicationService;
    private IModuleService moduleService;
    private IAllUserService allUserService;
    private IFileUploadService fileUploadService;
    private IRuleImplementService ruleImplementService;

    private File upload;
    private String uploadFileName;
    // TODO 路径从配置文件读
    private String path = PropertiesUtil.getApplicationUploadDir().getAbsolutePath();
    private Date createtime;
    private String result;
    private String errorMsg;
    private boolean success;

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public List<?> getDatas() {
        return datas;
    }

    public void setDatas(List<?> datas) {
        this.datas = datas;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public Application getApplication() {
        return application;
    }

    public void setApplication(Application application) {
        this.application = application;
    }

    public Module getModule() {
        return module;
    }

    public void setModule(Module module) {
        this.module = module;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    public IFileUploadService getFileUploadService() {
        return fileUploadService;
    }

    public void setFileUploadService(IFileUploadService fileUploadService) {
        this.fileUploadService = fileUploadService;
    }

    private String saveFile(String path) throws Exception {
        String username = userName.trim().replace("\"", "");
        File dir = new File(path + "\\" + username + "\\" + appName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // int pos = uploadFileName.lastIndexOf(".");
        // uploadContentType = uploadFileName.substring(pos + 1);//文件后缀名
        createtime = new Date();// 当前日期

        InputStream is = new FileInputStream(upload);
        OutputStream os = new FileOutputStream(new File(dir, uploadFileName));
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = is.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        is.close();
        os.close();
//        return path.replace("\\\\", "\\") + username.trim() + "\\" + appName + "\\" + uploadFileName;
        return username.trim() + "\\" + appName + "\\" + uploadFileName;
    }

    public IApplicationService getApplicationService() {
        return applicationService;
    }

    public void setApplicationService(IApplicationService applicationService) {
        this.applicationService = applicationService;
    }

    public IModuleService getModuleService() {
        return moduleService;
    }

    public void setModuleService(IModuleService moduleService) {
        this.moduleService = moduleService;
    }

    public IAllUserService getAllUserService() {
        return allUserService;
    }

    public void setAllUserService(IAllUserService allUserService) {
        this.allUserService = allUserService;
    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
        System.out.println("上传到tomcat中的临时文件名：" + upload.getPath());
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
        System.out.println("上传的文件名：" + uploadFileName);
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public IRuleImplementService getRuleImplementService() {
        return ruleImplementService;
    }

    public void setRuleImplementService(IRuleImplementService ruleImplementService) {
        this.ruleImplementService = ruleImplementService;
    }

    public String addApplication() {
        JSONObject json = JSONObject.fromObject(datas.get(0));
        String username = userName.trim().replace("\"", "");
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(new Date());
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        ts = Timestamp.valueOf(dateStr);
        try {
            // 创建application
            Application application_tmp = (Application) JSONObject.toBean(json, Application.class);// 将json对象转换为javaBean
            if (this.getApplicationService().isNameExisted(application_tmp.getAppName())) {
                this.setSuccess(false);
                this.setErrorMsg("应用名称已存在！");
                return SUCCESS;
            }
            application_tmp.setAppCreateTime(dateStr);
            application_tmp.setAllUser(this.getAllUserService().findUserByName(username));
            this.getApplicationService().addApplication(application_tmp);

            // 保存文件
            String fileUrl = saveFile(path);
            // TODO : 检查文件名重复
            
            // 创建application的默认module
            Module module_tmp = new Module();
            module_tmp.setModName(application_tmp.getAppName());
            module_tmp.setApplication(application_tmp);
            module_tmp.setModCreateTime(ts);
            module_tmp.setModFileUrl(fileUrl);
            this.getModuleService().addModule(module_tmp);

            // TODO ：分析war包，根据jar建立剩余的module
            
            this.setResult(application_tmp.getAppId().toString());
            this.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            this.setErrorMsg("上传失败！");
            this.setSuccess(false);
        }
        return SUCCESS;
    }

    public List<Module> analyzeFile() {
        return null;
    }

    @Override
    public String execute() throws Exception {

        this.saveFile(path);
        // TODO
        // 使用json传递application和module

        if (this.fileUploadService.isFileUpload(application, module)) {
            result = "{success:1}";
        } else {
            result = "{success:0, errorMsg:'上传失败!'}";
        }
        return SUCCESS;
    }
}
